//
//  DZYApi.swift
//  globalcarbusiness
//
//  Created by dongzhenyu on 2017/9/5.
//  Copyright © 2017年 dongzhenyu. All rights reserved.
//

import Foundation
import Moya
import Moya_ObjectMapper


// MARK: - JSON 序列化
private func JOSNResponseDataFormatter(_ data: Data) -> Data {
    
    do {
        let dataJSON = try JSONSerialization.jsonObject(with: data)
        let prettyData = try JSONSerialization.data(withJSONObject: dataJSON, options: .prettyPrinted)
        return prettyData
    } catch {
        return data
    }
    
}

/* Moya 默认的 Provider（不打印请求信息和返回的 json 数据） */
//let DZYProvider = MoyaProvider<DZYApi> (endpointClosure: endpointClosure)
/* 自定义 Provider（打印请求信息和返回 json 数据，并且序列化 json 数据） */
let DZYProvider = MoyaProvider<DZYApi>(endpointClosure: endpointClosure, plugins: [NetworkLoggerPlugin(verbose: true, responseDataFormatter: JOSNResponseDataFormatter)])


let endpointClosure = { (target: DZYApi) -> Endpoint<DZYApi> in
    // 获取默认配置信息
    let defaultEndpoint = MoyaProvider.defaultEndpointMapping(for: target)
    let url = target.baseURL.appendingPathComponent(target.path).absoluteString
    
    // 判断 "?" 是否被转义
    let original = "?"
    let modified = "%3F"
    var originalURL = url
    if originalURL.contains(modified) {
        // 恢复转义后的字符串为原始值
        originalURL = url.replacingOccurrences(of: modified, with: original)
    }
    
    /* 0：浏览器、1：微信、2：QQ、3：微博、4：小程序、5：Android应用、6：iOS应用 */
    var parameters = target.parameters
//    parameters?.updateValue("6", forKey: "client_name")
    
    return Endpoint(
        url: originalURL,
        sampleResponseClosure: { .networkResponse(200, target.sampleData) },
        method: target.method,
        parameters: parameters,
        parameterEncoding: target.parameterEncoding
    )
}

// 统一把请求的api 以枚举形式来选择各个api
enum DZYApi {
    case test
    case STORE_DETAILS_API
    case topicMessage(a: String, c: String, type: String)
}

extension DZYApi: TargetType {

    var baseString: String {
        return "http://api.budejie.com/api"
    }
    
    var baseURL: URL {
        return URL(string: baseString)!
    }
    
    var path: String {
        switch self {
        case .test:
            return ""
        case .STORE_DETAILS_API:
            return "/store/api/getHomeDetailes.json?orderResult=0"
        case .topicMessage:
            return "/api_open.php"
        }
        
       
    }
    
    var method: Moya.Method {
        switch self {
        case .test:
            return .post
        case .STORE_DETAILS_API, .topicMessage:
            return .get
        }
    }
    
    /// The parameters to be incoded in the request.
    var parameters: [String : Any]? {
        switch self {
        case .test:
            return ["haha": "ceshi"]
        case .STORE_DETAILS_API:
            return [:]
        case .topicMessage(let a, let c, let type):
            return [
                "a": a,
                "c": c,
                "type": type
            ]
        }
        
    }

    
    var parameterEncoding: ParameterEncoding {
        return URLEncoding.default
    }
    
    var task: Task {
        return .request
    }
    
    var sampleData: Data {
        switch self {
        case .test:
            return stubbedResponse("test")
        case .STORE_DETAILS_API:
            return stubbedResponse("STORE_DETAILS_API")
        case .topicMessage:
            return stubbedResponse("topicMessage")
            
        }
        
    }
    
    var validate: Bool {
        return false
    }
}

// MARK: - Provider support
func stubbedResponse(_ filename: String) -> Data! {
    
    @objc class CDTestClass: NSObject {}
    
    let bundle = Bundle(for: CDTestClass.self)
    let path = bundle.path(forResource: filename, ofType: "json")
    return (try? Data(contentsOf: URL(fileURLWithPath: path!)))
}


private extension String {
    var URLEscapedString: String {
        return addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)!
    }
}

func url(_ route: TargetType) -> String {
    return route.baseURL.appendingPathComponent(route.path).absoluteString
}

